import {Component, ElementRef, NgZone, OnDestroy, OnInit} from '@angular/core';
import {AlertController, Events, NavController, ToastController} from '@ionic/angular';
import {BaseTabPage} from '../../common/baseTabPage';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {AppConfig} from '../../common/app-config.enum';
import {fromPromise} from 'rxjs/internal/observable/fromPromise';
import {Storage} from '@ionic/storage';
import {mergeMap} from 'rxjs/internal/operators';
import {select, Store} from '@ngrx/store';
import * as networkReducer from '../../reducers/network.reducer';

/**
 * 我的
 */
@Component({
  selector: 'app-user',
  templateUrl: './user.page.html',
  styleUrls: ['./user.page.scss'],
})
export class UserPage extends BaseTabPage implements OnInit, OnDestroy {

  public user: any = {}; // 用户基础数据(账号，头像等)
  public userFund: any = {}; // 当前角色账户数据
  public userRole = 1; // 当前角色
  public isLend = true; // 当前角色是否为出借人
  public greetKey = 'morning';
  public greetings = {
    morning: '早上好，一束阳光照在身，一天都会很开心',
    noon: '该补充能量了，愿中午阳光带给你明媚的温暖',
    afternoon: '下午好，偶尔也活动活动，让自己放松一下',
    evening: '晚上好，送上温馨的问候，洗去你一天的疲惫',
    other: '夜已深了，早点休息吧'
  };
  private timmer: any;

  private orangeObj = {r: '243', g: '121', b: '56'};

  private blueObj = {r: '37', g: '76', b: '140' };
  // 注册时间对象
  registerTime: any = {};
  // 注册至今天数
  registerDays = null;

  constructor(public zone: NgZone,
              public elRef: ElementRef,
              private events: Events,
              private storage: Storage,
              private navCtrl: NavController,
              private alertCtrl: AlertController,
              private toastCtrl: ToastController,
              private service$: HttpService,
              private store: Store<networkReducer.NetworkState>
  ) {
    super(zone, elRef);
    // 只变化header背景不变化标题文字
    this.headerChangedPart = {
      ionToolbar: true,
      ionTitle: false
    };
    // 侦听网络状态变化
    this.store.pipe(select(networkReducer.getNetwork))
      .subscribe(networkState => {
        if (networkState.status  === 1) {
          this.getData();
        }
      });
    // 手势解锁后重新加载数据(防止进入手势解锁页时就TAB中的页面，解锁成功后数据不刷新)
    this.events.subscribe(AppConfig.TOPIC_TAB_REFRESH, () => {
      this.getData();
    });
    // 用户基础信息和账户数据变化
    this.events.subscribe(AppConfig.TOPIC_USER_FUNC, () => {
      this.getData();
    });
    // 用户头像变更
    this.events.subscribe(AppConfig.TOPIC_USER_AVATAR, photo => {
      this.user.photo = this.HOST + photo;
    });
  }

  ngOnInit() {
    // 获取header中的元素
    this.getTopElement();
    // 每隔一段时间，检测当前时段
    this.checkNow();
    this.timmer = setInterval(() => {
      this.checkNow();
    }, 600000);
  }

  ngOnDestroy() {
    // 取消时段检测
    clearInterval(this.timmer);
    // 取消订阅
    this.events.unsubscribe(AppConfig.TOPIC_TAB_REFRESH);
    this.events.unsubscribe(AppConfig.TOPIC_USER_FUNC);
  }

  // 下拉刷新
  doRefresh(event?) {
    this.getData(event);
  }

  // 获取用户基础数据和账户数据
  private getData(event?) {
    fromPromise(this.storage.get(AppConfig.USER_INFO))
      .pipe(
        mergeMap(userInfo => {
          this.userRole = userInfo[AppConfig.USER_ROLE_KEY];
          this.isLend = this.userRole === 1; // 判断是否为出借人
          if (this.isLend) {
            this.rgbObj = this.blueObj; // 出借人设置顶部为蓝色主题
          } else {
            this.rgbObj = this.orangeObj;
          }
          return this.service$.doRequest(UrlAndOPT.auth_userInfo_func, {userRole: this.userRole});
        })
      )
      .subscribe(obj => {
        if (obj) {
          this.user = obj;
          this.user.photo = this.HOST + this.user.photo;
          this.userFund = this.user['userFundInfo'];
          this.registerTime = this.user['registerTime'];
          // 计算天数
          const byDay = 1000 * 60 * 60 * 24;
          const day = Math.floor((new Date().getTime() - this.registerTime['time']) / byDay);
          this.registerDays = day || 1;
        }
        if (event) {  // 如果为下拉刷新，关闭下拉组件
          event.target.complete();
        }
      }, () => {
        if (event) {
          event.target.complete();
        }
      });
  }

  // 根据日期变化问候语
  private checkNow() {
    const hours = new Date().getHours();
    if (hours > 6 && hours < 23) {
      if (hours > 18) {
        this.greetKey = 'evening';
      } else if (hours > 11) {
        this.greetKey = 'afternoon';
      } else {
        this.greetKey = 'morning';
      }
    } else {
      this.greetKey = 'other';
    }
  }

  // 跳转头像编辑页
  pushAvatarPage() {
    this.navCtrl.navigateForward(['/auth/user-avatar', {photo: this.user['photo']}]);
  }

  async showToast(txt: string) {
    const toast = await this.toastCtrl.create({
      message: txt,
      position: AppConfig.TOAST_POSITION,
      duration: AppConfig.TOAST_DURATION * 1
    });
    return toast.present();
  }

}
